package com.lottery.im.module.chat.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.lottery.im.MyApplication;
import com.lottery.im.R;
import com.lottery.im.api.ApiClient;
import com.lottery.im.api.observer.BaseObserver;
import com.lottery.im.api.result.entity.UserInfo;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.module.tim.presenter.FriendshipManagerPresenter;
import com.lottery.im.util.StatusBarHelper;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.ext.group.TIMGroupManagerExt;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 修改单文本的情况(修改备注名、群名片、群名称、昵称)
 */
public class ModifySingleTextFragment extends BaseSwipeFragment implements TIMCallBack {

  private final static String ID_KEY = "ID_KEY";
  private final static String TEXT_KEY = "TEXT_KEY";
  private final static String TYPE_KEY = "TYPE_KEY";

  public static ModifySingleTextFragment create(String id,String text,  OpType type) {
    ModifySingleTextFragment fragment = new ModifySingleTextFragment();
    Bundle b = new Bundle();
    b.putString(ID_KEY, id);
    b.putString(TEXT_KEY, text);
    b.putSerializable(TYPE_KEY, type);
    fragment.setArguments(b);
    return fragment;
  }

  @BindView(R.id.et_name) EditText mEtName;
  @BindView(R.id.tv_title) TextView mTvTitle;

  private String mId;
  private OpType mType;

  public final static String INPUT_CONTENT_KEY = "INPUT_CONTENT_KEY";

  @Override protected int getLayoutResId() {
    return R.layout.fragment_modify_single_text;
  }

  @Override protected void initPresenter() {
    StatusBarHelper.setStatusBarDarkMode(getActivity());
    initView();
  }

  private void initView() {
    mId = getArguments().getString(ID_KEY);
    String text = getArguments().getString(TEXT_KEY);
    mEtName.setText(text);
    mType = (OpType) getArguments().getSerializable(TYPE_KEY);
    if (mType == OpType.REMARKNAME) {
      mTvTitle.setText("修改备注名");
    } else if (mType == OpType.NAMECARD) {
      mTvTitle.setText("编辑群名片");
    } else if (mType == OpType.GROUPNAME) {
      mTvTitle.setText("修改群聊名称");
    } else if (mType == OpType.NICKNAME) {
      mTvTitle.setText("修改昵称");
    }
  }

  @OnClick({ R.id.iv_back, R.id.tv_ok }) public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.iv_back:
        popBackStack();
        break;
      case R.id.tv_ok:
        submit();
        break;
    }
  }

  private void submit() {
    String name = mEtName.getText().toString();

    if (TextUtils.isEmpty(name)) {

      if (mType != OpType.REMARKNAME && mType != OpType.NAMECARD) {
        showToast("请输入1-24个字符");
        return;
      }
    }

    showLoadingDialog();
    if (mType == OpType.REMARKNAME) {
      modifyRemarkName(name);
    } else if (mType == OpType.NAMECARD) {
      modifyNameCard(name);
    } else if (mType == OpType.GROUPNAME) {
      modifyGroupName(name);
    } else if (mType == OpType.NICKNAME) {
      modifyNickName(name);
    }
  }

  // 修改备注名
  private void modifyRemarkName(String name) {
    // 修改备注名
    FriendshipManagerPresenter.setRemarkName(mId, name, this);
  }

  // 修改群名片
  private void modifyNameCard(String name) {
    //  修改自己的群名片
    TIMGroupManagerExt.ModifyMemberInfoParam param =
        new TIMGroupManagerExt.ModifyMemberInfoParam(mId,
            MyApplication.getInstance().getThirdAccId());
    param.setNameCard(name);
    TIMGroupManagerExt.getInstance().modifyMemberInfo(param, this);
  }

  // 修改群名称
  private void modifyGroupName(String name) {
    TIMGroupManagerExt.ModifyGroupInfoParam param =
        new TIMGroupManagerExt.ModifyGroupInfoParam(mId);
    param.setGroupName(name);
    TIMGroupManagerExt.getInstance().modifyGroupInfo(param, this);
  }

  // 修改昵称
  private void modifyNickName(String name) {
    Map<String, String> map = new HashMap<>();
    map.put("userId", MyApplication.getInstance().getUserInfo().getUserId());
    map.put("token", MyApplication.getInstance().getToken());
    map.put("updateUserName", name);

    ApiClient.getApiRetrofitInstance()
        .updateUserInfoForFront(map)
        .throttleFirst(2, TimeUnit.SECONDS)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .compose(this.bindToLifecycle())
        .subscribe(new BaseObserver<UserInfo>() {
          @Override public void onStart() {
            showLoadingDialog();
          }

          @Override public void onSuccess(UserInfo userInfo) {

            TIMFriendshipManager.ModifyUserProfileParam param =
                new TIMFriendshipManager.ModifyUserProfileParam();
            param.setNickname(userInfo.getUserName());

            TIMFriendshipManager.getInstance().modifyProfile(param, new TIMCallBack() {
              @Override
              public void onError(int code, String desc) {
                showToast("修改失败，请稍后再试～");
                cancelLoadingDialog();
              }

              @Override
              public void onSuccess() {
                UserInfo userInfo1 = MyApplication.getInstance().getUserInfo();
                userInfo1.setUserName(userInfo.getUserName());
                userInfo1.setThirdUserName(userInfo.getUserName());
                UserInfo.refreshInfo(mActivity, userInfo1);
                Intent data = new Intent();
                data.putExtra(INPUT_CONTENT_KEY, mEtName.getText().toString());
                setFragmentResult(RESULT_OK, data);
                popBackStack();
                cancelLoadingDialog();
              }
            });
          }

          @Override public void onFail(String code, String msg) {
            showToast(msg);
            cancelLoadingDialog();
          }

          @Override public void onException(String msg) {

          }

          @Override public void onFinish() {

          }
        });
  }

  @Override public void onError(int i, String s) {
    cancelLoadingDialog();
    showToast("修改失败，请稍后再试");
  }

  @Override public void onSuccess() {
    cancelLoadingDialog();
    Intent data = new Intent();
    data.putExtra(INPUT_CONTENT_KEY, mEtName.getText().toString());
    setFragmentResult(RESULT_OK, data);
    popBackStack();
  }

  /**
   * 操作类型
   */
  public enum OpType {
    REMARKNAME, //备注名
    NAMECARD,   // 群名片
    GROUPNAME,  // 群名称
    NICKNAME    // 昵称
  }
}
